﻿using GalaSoft.MvvmLight;
using System.Windows.Controls;
using SGTLightAccent.Web.Models;
using SGTLightAccent.Web.Services;
using System;
using System.Linq;
using GalaSoft.MvvmLight.Messaging;
using SGTLightAccent.Models;
using System.ServiceModel.DomainServices.Client;
using System.Collections.ObjectModel;
using System.Windows.Data;
using System.Windows.Printing;
using System.Windows.Media;
using SGTLightAccent.Plantillas;
using GalaSoft.MvvmLight.Command;
using Lite.ExcelLibrary.SpreadSheet;
using System.IO;

namespace SGTLightAccent.ViewModel
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm/getstarted
    /// </para>
    /// </summary>
    public class ClientesViewModel : ViewModelBase
    {
        private static ClientesViewModel _instance = null;
        private Carga _cargaSeleccionada;
        private SGTDomainContext contexto;
        private ObservableCollection<Bodega> _bodegas;
        private EntitySet<Remito_Barco> _remitos;
        private PagedCollectionView _remitosPaginado;
        private bool _estaCargando;
        private decimal _pesoNeto;
        private decimal _pesoANP;
        public RelayCommand BotonImprimirRemitos { get; private set; }
        /// <summary>
        /// Initializes a new instance of the ClientesViewModel class.
        /// </summary>
        /// 

        #region Fields

        public decimal PesoANP
        {
            get { return _pesoANP; }
            set
            {

                _pesoANP = value;
                RaisePropertyChanged("PesoANP");


            }
        }

        public decimal PesoNeto
        {
            get { return _pesoNeto; }
            set
            {

                _pesoNeto = value;
                RaisePropertyChanged("PesoNeto");


            }
        }

        public Carga CargaSeleccionada
        {
            get { return _cargaSeleccionada; }
            set
            {
                //if (value != null)
                //{
                    _cargaSeleccionada = value;
                    RaisePropertyChanged("CargaSeleccionada");
                //}


            }
        }

        public bool EstaCargando
        {
            get { return _estaCargando; }
            set
            {

                _estaCargando = value;
                RaisePropertyChanged("EstaCargando");


            }
        }

        #endregion

        #region Entidades

        public EntitySet<Remito_Barco> Remitos
        {
            get { return _remitos; }
            set
            {

                _remitos = value;


                RaisePropertyChanged("Remitos");


            }
        }

        public PagedCollectionView RemitosPaginado
        {
            get { return _remitosPaginado; }
            set
            {

                _remitosPaginado = value;

                RaisePropertyChanged("RemitosPaginado");


            }
        }



        public ObservableCollection<Bodega> Bodegas
        {
            get { return _bodegas; }
            set
            {

                _bodegas = value;
                RaisePropertyChanged("Bodegas");
                


            }
        }

        #endregion

        public static ClientesViewModel getInstance()
        {
            if (_instance == null)
                _instance = new ClientesViewModel();
            return _instance;
        }

       
        protected ClientesViewModel()
        {
            if (IsInDesignMode)
            {
            ////    // Code runs in Blend --> create design time data.
           }
            else
            {
                contexto = new SGTDomainContext();
                Messenger.Default.Register<EnvioMensaje>(this, msg => procesarMensaje(msg));
                BotonImprimirRemitos = new RelayCommand(exportarAExcel);
                //loadDescargaActual();
           
            }
        }

        private void loadDescargaActual()
        {

            if (Bodegas == null)
                Bodegas = new ObservableCollection<Bodega>();
           
            contexto.Load<Carga>(contexto.GetUltimaCargaQuery(),ret => 
                {
                    CargaSeleccionada = ret.Entities.FirstOrDefault();
                    contexto.Load<Remito_Barco>(contexto.GetRemito_Barco_CargaQuery(CargaSeleccionada.Id), LoadBehavior.RefreshCurrent, LoadOperation =>
                        {
                            contexto.Load<Barco>(contexto.GetBarcoIDQuery((int)CargaSeleccionada.Barco_FK));
                            //contexto.Load<Bodega>(contexto.GetBodegaByCargaQuery(CargaSeleccionada.Id));
                           
                            contexto.Load<Bodega>(contexto.GetBodegaByCargaQuery(CargaSeleccionada.Id), bods =>
                                {
                                    Bodegas.Clear();
                                    foreach (Bodega b in contexto.Bodegas)
                                    {
                                       
                                        Bodegas.Add(b);
                                    }
                                },null);
                            
                            
                            //RaisePropertyChanged("CargaSeleccionada");
                           
                            
                        },null);
                   
                }, null);
            
            
        }

        private void procesarMensaje(EnvioMensaje msg)
        {

            if (msg.texto.Equals("loadDescargaActual"))
            {
                loadDescargaActual();
                cargarRemitos();
            }
          
            
         
        }

        private void cargarRemitos()
        {
            //EstaCargando = true;
            contexto.Load<Mercaderia>(contexto.GetMercaderiaQuery());
            contexto.Load<Deposito>(contexto.GetDepositoQuery());
            if (CargaSeleccionada != null)
            {
                int id = CargaSeleccionada.Id;
                
                contexto.Load<Bodega>(contexto.GetBodegaByCargaQuery(id), LoadOperation =>
                {
                    if (Remitos == null || Remitos.Count != contexto.Remito_Barcos.Count)
                    {
                        EstaCargando = true;
                        if (Remitos != null)
                            Remitos.Clear();
                        cargarRemitosInterno(id);
                    }
                    //else
                      //  EstaCargando = false;
                    
                }, null);

            }
           
        }

        private void cargarRemitosInterno(int idCarga)
        {
            contexto.Load<Remito_Barco>(contexto.GetRemito_Barco_CargaQuery(idCarga), LoadOperation =>
            {
                Remitos = contexto.Remito_Barcos;
                recalcularPesos();
                EstaCargando = false;
                RemitosPaginado = new PagedCollectionView(Remitos);

            }, null);
        }
        private void recalcularPesos()
        {
            PesoNeto = 0;
            PesoANP = 0;
            decimal PesoTara = 0;
            foreach (Remito_Barco r in Remitos)
            {
                if (r.Peso_ANP != null && r.PesoNeto != null && r.Tara != null)
                {
                    PesoNeto += (decimal)r.Bruto1 + (decimal)r.Bruto2;
                    PesoANP += (decimal)r.Peso_ANP;
                    PesoTara += (decimal)r.Tara_1 + (decimal)r.Tara_2;
                }
            }
            PesoNeto = PesoNeto - PesoTara;
        }

        private void imprimirRemito()
        {
            PlantillaReporteRemitos plantilla = new PlantillaReporteRemitos();
            PrintDocument pd = new PrintDocument();
            //FechaAhora = DateTime.Now;
            // Set the printable area

            Canvas c = new Canvas();
            c.Width = 797.8;
            c.Height = 1123.2;
            ScaleTransform scaleTransform = new ScaleTransform();
            scaleTransform.ScaleX = 0.9;
            scaleTransform.ScaleY = 0.9;
            plantilla.RenderTransform = scaleTransform;




            pd.PrintPage += (s, args) =>
            {


                c.Children.Add(plantilla);
                args.PageVisual = c;
                args.HasMorePages = false;

            };

            pd.EndPrint += (s, args) =>
            {


            };

            // Print the document
            pd.Print("Remito");
        }

        private void imprimirV2()
        {
            PrintDocument docDataGrid = new PrintDocument();
            
            docDataGrid.PrintPage += new EventHandler<PrintPageEventArgs>(docDataGrid_PrintPage);
            docDataGrid.Print("Reporte remitos");
        }

        private void exportarAExcel()
        {
              // open file dialog to select an export file.   
            SaveFileDialog sDialog = new SaveFileDialog();
            sDialog.Filter = "Excel Files(*.xls)|*.xls";

            if (sDialog.ShowDialog() == true)
            {

                // create an instance of excel workbook
                
                Workbook workbook = new Workbook();
                
                // create a worksheet object
                Worksheet worksheet = new Worksheet("Remitos");

                
                Int16 RowCount = 0;

                //Writing Column Names 

                worksheet.Cells[0, 0] = new Cell("Fecha");
                worksheet.Cells[0, 1] = new Cell("N° Remito");
                worksheet.Cells[0, 2] = new Cell("Matricula Camión");
                worksheet.Cells[0, 3] = new Cell("Matricula Zorra");
                worksheet.Cells[0, 4] = new Cell("Hora de salida");
                worksheet.Cells[0, 5] = new Cell("Hora de llegada");
                worksheet.Cells[0, 6] = new Cell("Bruto 1");
                worksheet.Cells[0, 7] = new Cell("Bruto 2");
                worksheet.Cells[0, 8] = new Cell("Tara 1");
                worksheet.Cells[0, 9] = new Cell("Tara 2");
                worksheet.Cells[0, 10] = new Cell("NETO");
                worksheet.Cells[0, 11] = new Cell("Producto");
                worksheet.Cells[0, 12] = new Cell("Peso ANP");


                foreach (Remito_Barco r in Remitos)
                {

                    RowCount++;
                    if (r.Hora_Salida != null)
                        worksheet.Cells[RowCount, 0] = new Cell(r.Hora_Salida.Value.ToShortDateString());
                    worksheet.Cells[RowCount, 1] = new Cell(r.Numero_Remito_Carga);
                    worksheet.Cells[RowCount, 2] = new Cell(r.Matricula_Camion, CellFormat.General);
                    worksheet.Cells[RowCount, 3] = new Cell(r.Matricula_2, CellFormat.General);
                    if (r.Hora_Salida != null)
                        worksheet.Cells[RowCount, 4] = new Cell(r.Hora_Salida.Value.ToShortTimeString());
                    if (r.Hora_Llegada != null)
                    worksheet.Cells[RowCount, 5] = new Cell(r.Hora_Llegada.Value.ToShortTimeString());
                    worksheet.Cells[RowCount, 6] = new Cell(r.Bruto1, CellFormat.General);
                    worksheet.Cells[RowCount, 7] = new Cell(r.Bruto2, CellFormat.General);
                    worksheet.Cells[RowCount, 8] = new Cell(r.Tara_1, CellFormat.General);
                    worksheet.Cells[RowCount, 9] = new Cell(r.Tara_2, CellFormat.General);
                    if (r.Bodega != null)
                        worksheet.Cells[RowCount, 10] = new Cell(r.Bodega.Mercaderia.Nombre, CellFormat.General);
                    worksheet.Cells[RowCount, 11] = new Cell(r.PesoNeto, CellFormat.General);
                    worksheet.Cells[RowCount, 12] = new Cell(r.Peso_ANP, CellFormat.General);

                }


                //add worksheet to workbook
                workbook.Worksheets.Add(worksheet);
                // get the selected file's stream
                Stream sFile = sDialog.OpenFile();
                workbook.Save(sFile);
            }
        }

        void docDataGrid_PrintPage(object sender, PrintPageEventArgs e)
        {

            // Stretch to the size of the printed page
            PlantillaReporteRemitos plantilla = new PlantillaReporteRemitos();

            plantilla.dataGrid2.Width = e.PrintableArea.Width;

            plantilla.dataGrid2.Height = e.PrintableArea.Height;

            // Assign the XAML element to be printed

            e.PageVisual = plantilla;

            // Specify whether to call again for another page

            e.HasMorePages = false;

        }

        ////public override void Cleanup()
        ////{
        ////    // Clean own resources if needed

        ////    base.Cleanup();
        ////}
    }
}